
package pe.pucp.plugin.common;

import java.io.InputStream;
import java.io.OutputStream;
import javax.swing.JOptionPane;
import javax.swing.text.JTextComponent;

/**
 *
 * @author Diego
 */
public class TextComponentReaderThread extends ReaderThread {
    private JTextComponent text;
    private boolean showLastOnly;
    private StringBuilder sb;
    private WriterThread wt;
    private MessageReaderThread errorThread;
    private String userCommand;
    private boolean nuevoUserCommand;

    public TextComponentReaderThread(InputStream is, OutputStream os, InputStream es, JTextComponent text, boolean showLastOnly) {
        super(is);
        wt = new WriterThread(os);
        errorThread = new MessageReaderThread(es);
        this.text = text;
        this.showLastOnly = showLastOnly;
        if (!showLastOnly) {
            sb = new StringBuilder("");
        }
        this.start();
        errorThread.start();
        wt.start();

    }

    public void nuevoComando(String c) {
        userCommand = c;
        nuevoUserCommand = true;
        wt.nuevaSalida(c);
    }

    private String prepareTextoAImprimir(String entrada) {
        StringBuilder sb = new StringBuilder("");
        if (nuevoUserCommand) {
            sb.append(userCommand);
            sb.append("\n");
            nuevoUserCommand = false;
        }
        sb.append(entrada);
        sb.append("\n");
        return sb.toString();
    }

    @Override
    protected String nuevaEntrada(String entrada) {

        String en = prepareTextoAImprimir(entrada);
        if (showLastOnly) {
            text.setText(en);
            text.repaint();
            return en;
        }
        sb.append(en);
        String s = sb.toString();
        text.setText(s);
        text.repaint();
        return s;
    }
}
